package com.hnevc.broadcastreceiverdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private MyBroadCastReceiver mReceiver;
    private IntentFilter mFilter;

    private Button mBtnSendBroadCast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        mReceiver = new MyBroadCastReceiver();
        mFilter = new IntentFilter();
        mFilter.addAction("com.hnevc.broadcastreceiver");
        registerReceiver(mReceiver, mFilter);



        mBtnSendBroadCast = (Button) findViewById(R.id.id_btn_send_broadast);
        mBtnSendBroadCast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //创建intent
                Intent intent = new Intent();
                intent.setAction("com.hnevc.broadcastreceiver");
                intent.putExtra("msg","自定义广播");
                //发送广播
                sendBroadcast(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //动态注销
        unregisterReceiver(mReceiver);
    }

    //1 定义一个BroadCastReceiver类的子类
    class MyBroadCastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String data = intent.getStringExtra("msg");
            Toast.makeText(MainActivity.this, "接收到消息："+data, Toast.LENGTH_SHORT).show();
        }
    }
}
